<template>
    <div class="user-page" v-if="user">
        <!-- 顶部个人信息区 -->
        <div class="user-header">
            <div class="user-header-bg"></div>
            <div class="user-info-container">
                <div class="avatar-container">
                    <van-image
                        round
                        fit="cover"
                        class="avatar"
                        :src="user.avatarUrl || 'https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg'"
                    />
                    <div class="edit-avatar-btn" @click="toUserInfo">
                        <van-icon name="edit" color="rgb(238, 10, 36)" />
                    </div>
                </div>
                <div class="user-basic-info">
                    <div v-if="!user.username" class="username" @click="toLogin">点击登录</div>
                    <div v-else class="username">{{ user.username }}</div>
                    <div class="user-id">ID: {{ user.userId }}</div>
                </div>
                <div class="user-stat">
                    <div class="stat-item">
                        <div class="stat-value">{{ tagList.length }}</div>
                        <div class="stat-label">标签</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-value">0</div>
                        <div class="stat-label">队伍</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-value">0</div>
                        <div class="stat-label">动态</div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 标签展示区 -->
        <div class="tags-section">
            <div class="section-title">我的标签</div>
            <div class="tags-container">
                <van-tag 
                    v-for="tag in tagList" 
                    :key="tag" 
                    closeable 
                    round
                    size="medium" 
                    color="rgb(238, 10, 36)"
                    @close="delTag(tag)"
                >
                    {{ tag }}
                </van-tag>
                <van-tag 
                    round
                    color="rgb(238, 10, 36)" 
                    plain
                    size="medium" 
                    @click="showAddTag"
                >
                    +添加
                </van-tag>
            </div>
        </div>
        
        <!-- 功能区 -->
        <div class="feature-section">
            <div class="section-title">功能导航</div>
            <van-grid :column-num="3" :border="false" :gutter="6">
                <van-grid-item
                    v-for="(item, index) in menuItems"
                    :key="index"
                    :icon="item.icon"
                    :text="item.text"
                    :to="item.url"
                />
            </van-grid>
        </div>
        
        <!-- 其他操作区 -->
        <div class="action-section">
            <van-cell is-link title="退出登录" @click="logout" center>
                <template #icon>
                    <van-icon name="close" class="action-icon logout-icon" />
                </template>
            </van-cell>
        </div>
        
        <!-- 添加标签弹窗 -->
        <van-popup
            v-model:show="isShowAddTag"
            round
            position="bottom"
            :style="{ height: '30%' }"
        >
            <div class="popup-header">添加标签</div>
            <van-cell-group inset>
                <van-field
                    v-model="tag"
                    center
                    placeholder="请输入标签名"
                    maxlength="10"
                    show-word-limit
                >
                    <template #button>
                        <van-button size="small" color="rgb(238, 10, 36)" @click="submitAddTag">提交</van-button>
                    </template>
                </van-field>
            </van-cell-group>
        </van-popup>
    </div>
</template>

<script setup lang="ts">
import {onMounted, ref} from "vue";
import {useRouter} from "vue-router";
import {getCurrentUser} from "../services/user";
import {showConfirmDialog, showFailToast, showSuccessToast} from "vant";
import {addTag, removeTag} from "../services/tags";

const user = ref();
const router = useRouter();
const tagList = ref([]);
const tag = ref('');
const isShowAddTag = ref(false);

// 定义菜单项
const menuItems = [
    { icon: "manager-o", text: "个人资料", url: "/user/info" },
    { icon: "flag-o", text: "创建的队伍", url: "/user/team/create" },
    { icon: "friends-o", text: "加入的队伍", url: "/user/team/join" },
    { icon: "fire-o", text: "我的动态", url: "/user/dynamic" },
    { icon: "setting-o", text: "设置", url: "/user/settings" },
    { icon: "question-o", text: "关于我们", url: "/user/about" }
];

const toEdit = (editKey: string, editName: string, currentValue: string) => {
    router.push({
        path: '/user/edit',
        query: {
            editKey,
            editName,
            currentValue
        }
    })
}

const toUserInfo = () => {
    router.push('/user/info');
}

const toLogin = () => {
    router.push('/user/login');
}

const logout = () => {
    showConfirmDialog({
        title: '退出登录',
        message: '确定要退出登录吗？',
        theme: 'round-button',
    }).then(() => {
        // 处理退出登录逻辑
        showSuccessToast('已退出登录');
        // 这里应该有实际的退出登录API调用
        router.push('/user/login');
    }).catch(() => {
        // 取消
    });
}

onMounted(() => {
    loadUserInfo()
})

const loadUserInfo = async () => {
    const currentUser = await getCurrentUser()
    if (currentUser) {
        user.value = currentUser;
        tagList.value = JSON.parse(currentUser.tags);
    } else {
        showFailToast("获取用户信息失败")
    }
}

/**
 * 显示添加标签输入框
 */
const showAddTag = async () => {
    isShowAddTag.value = true
}

/**
 * 添加标签
 *
 * @param tag
 */
const submitAddTag = async () => {
    if (!tag.value.trim()) {
        showFailToast("标签名不能为空");
        return;
    }
    
    const result = await addTag({tag: tag.value, userId: user.value.userId})
    if (result && result.data && result.data.code === 0 && result.data.data) {
        showSuccessToast("添加成功")
        isShowAddTag.value = false
        tag.value = ''
        await loadUserInfo()
    } else {
        showFailToast("添加失败")
    }
};
/**
 * 删除标签
 *
 * @param tag
 */
const delTag = (tag: string) => {
    if (tagList.value.length > 1) {
        showConfirmDialog({
            message: `确定删除 ${tag} 标签吗？`,
            theme: 'round-button',
        }).then(async () => {
            // on confirm
            const result = await removeTag({tag, oldTags: tagList.value, userId: user.value.userId})
            if (result && result.data && result.data.code === 0 && result.data.data) {
                showSuccessToast("删除成功")
                await loadUserInfo()
            } else {
                showFailToast("删除失败")
            }
        }).catch(() => {
            // on cancel
        })
    } else {
        showFailToast("至少保留一个标签")
    }
};
</script>

<style scoped>
.user-page {
    background-color: #f7f8fa;
    min-height: 100vh;
    padding-bottom: 15px;
}

/* 顶部个人信息区 */
.user-header {
    position: relative;
    padding-bottom: 6px;
    background-color: #fff;
    border-radius: 0 0 16px 16px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    overflow: hidden;
    margin-bottom: 10px;
}

.user-header-bg {
    height: 85px;
    background: linear-gradient(to right, rgb(255, 96, 52), rgb(238, 10, 36));
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
}

.user-info-container {
    position: relative;
    padding: 15px 16px 8px;
    z-index: 1;
}

.avatar-container {
    position: relative;
    width: 70px;
    height: 70px;
    margin: 0 auto;
    margin-top: 25px;
}

.avatar {
    width: 100%;
    height: 100%;
    border: 3px solid #fff;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.edit-avatar-btn {
    position: absolute;
    right: -5px;
    bottom: -5px;
    width: 24px;
    height: 24px;
    border-radius: 50%;
    background-color: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
}

.user-basic-info {
    text-align: center;
    margin-top: 8px;
}

.username {
    font-size: 18px;
    font-weight: 600;
    color: #323233;
    margin-bottom: 2px;
}

.user-id {
    font-size: 12px;
    color: #969799;
}

.user-stat {
    display: flex;
    justify-content: space-around;
    margin-top: 15px;
    border-top: 1px solid #f5f5f5;
    padding-top: 10px;
}

.stat-item {
    text-align: center;
}

.stat-value {
    font-size: 16px;
    font-weight: 600;
    color: rgb(238, 10, 36);
}

.stat-label {
    font-size: 12px;
    color: #969799;
    margin-top: 2px;
}

/* 标签区 */
.tags-section {
    background-color: #fff;
    border-radius: 12px;
    padding: 12px;
    margin: 0 10px 10px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.section-title {
    font-size: 15px;
    font-weight: 600;
    color: #323233;
    margin-bottom: 12px;
    position: relative;
    padding-left: 12px;
}

.section-title::before {
    content: '';
    position: absolute;
    left: 0;
    top: 3px;
    height: 15px;
    width: 4px;
    background-color: rgb(238, 10, 36);
    border-radius: 2px;
}

.tags-container {
    display: flex;
    flex-wrap: wrap;
    gap: 6px;
}

/* 功能区 */
.feature-section {
    background-color: #fff;
    border-radius: 12px;
    padding: 12px;
    margin: 0 10px 10px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

/* 操作区 */
.action-section {
    background-color: #fff;
    border-radius: 12px;
    margin: 0 10px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    overflow: hidden;
}

.action-icon {
    margin-right: 10px;
    font-size: 16px;
}

.logout-icon {
    color: #ee0a24;
}

/* 添加标签弹窗 */
.popup-header {
    text-align: center;
    font-size: 16px;
    font-weight: 600;
    padding: 14px;
    border-bottom: 1px solid #f5f5f5;
}

:deep(.van-grid-item__content) {
    background-color: #f7f8fa;
    border-radius: 8px;
    padding: 12px 6px;
}

:deep(.van-grid-item__icon) {
    font-size: 24px;
    margin-bottom: 6px;
    color: rgb(238, 10, 36);
}

:deep(.van-grid-item__text) {
    color: #323233;
    font-size: 13px;
}

:deep(.van-cell) {
    font-size: 15px;
}
</style>
